package com.example.shop_2208.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.shop_2208.R
import com.example.shop_2208.adapter.CarAdapter
import com.example.shop_2208.databinding.FragmentCarBinding
import com.example.shop_2208.db.MyDbUtils
import com.example.shop_2208.mvvm.BaseFragment

class CarFragment : BaseFragment<FragmentCarBinding,CarViewModel>() {
    lateinit var carAdapter: CarAdapter
    override fun initData() {
        viewModel.selectSuccess.observe(this){
            if(it.code==200){
                carAdapter.data.clear()
                carAdapter.data.addAll(it.data)
                carAdapter.notifyDataSetChanged()
            }
        }
        viewModel.addSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
        viewModel.deleteSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
    }

    override fun initView() {
        //全选按钮的变化
        binding.cbAll.setOnCheckedChangeListener { buttonView, isChecked ->
            //点击全选按钮时，发生变化 --所有item的ischecked值更新
            binding.cbAll.setOnClickListener {
                carAdapter.data.forEach {
                    it.isChecked = isChecked
                }
                carAdapter.notifyDataSetChanged()
                totalMoney()//更新金额
            }
        }
        carAdapter = CarAdapter()
        binding.rvCar.adapter = carAdapter
        binding.rvCar.layoutManager = LinearLayoutManager(context)
        viewModel.selectCar()
        //点击实现数量加
        carAdapter.addChildClickViewIds(R.id.car_add,R.id.car_sub,R.id.car_delete,R.id.car_cb)
        carAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.car_add->{
                    //实现数量增加
                    carAdapter.data[position].count++//数据集合中的值发生变化
                    //页面发生变化---尽量不刷新适配器，防止当前选中状态发生变化
                    (carAdapter.getViewByPosition(position,R.id.car_count) as TextView).text = "${carAdapter.data[position].count}"
                    viewModel.addCar(carAdapter.data[position].goods_id,1)
                }
                R.id.car_sub->{
                    //实现数量减少 --数据中
                    if(carAdapter.data[position].count==1){
                        ToastUtils.showLong("当前数量为1，不能在减少了")
                        return@setOnItemChildClickListener
                    }
                    carAdapter.data[position].count--
                    (carAdapter.getViewByPosition(position,R.id.car_count) as TextView).text = "${carAdapter.data[position].count}"
                    viewModel.addCar(carAdapter.data[position].goods_id,-1)
                }
                R.id.car_delete->{
                    viewModel.deleteCar(carAdapter.data[position].id.toString())
                    //局部刷新---防止当前页面中的数据的选中状态发生变化
                    carAdapter.data.removeAt(position)
                    carAdapter.notifyItemRemoved(position)
                }
                R.id.car_cb->{
                    //修改checkbox的值为  原来的相反值
                    carAdapter.data[position].isChecked = !carAdapter.data[position].isChecked
                }
            }
            //无论点了数量加减、item的删除、item的选中  都需要更新金额变化 、下方全选按钮发生变化
            totalMoney()
            checkAll()
        }
        //点击立即购买，跳转到生成订单界面
        binding.toPay.setOnClickListener {
            val list = mutableListOf<Boolean>()
            carAdapter.data.forEach {
                list.add(it.isChecked)
            }
            if(true in list){
                //存在选中的商品待下单
                //先清空所有待下单的商品
                MyDbUtils.getDb().getOrderDao().delete()
                //将本次选中的商品生成待下单的订单
                carAdapter.data.forEach {
                    if(it.isChecked){
                        it.status = 0
                        MyDbUtils.getDb().getOrderDao().insert(it)
                    }
                }
                ARouter.getInstance().build("/app/OrderActivity").navigation()//跳转到订单页面
            }else{
                ToastUtils.showLong("至少选中一个商品")
            }
        }
    }

    private fun checkAll() {
        //用来接收所有数据的选中状态
        val list = mutableListOf<Boolean>()
        carAdapter.data.forEach {
            list.add(it.isChecked)
        }
        binding.cbAll.isChecked = false !in list
        //注释代码和上方代码效果一致
      /*  if(false in list){
            binding.cbAll.isChecked = false
        }else{
            binding.cbAll.isChecked = true
        }*/
    }

    private fun totalMoney() {
        var money = 0//合计金额
        carAdapter.data.forEach {
            if(it.isChecked){
                money+=it.count*it.goods_default_price
            }
        }
        binding.total.text = "合计：$money 元"

    }



    override fun getViewModel(): Class<CarViewModel> = CarViewModel::class.java

    override fun getLayout(): Int = R.layout.fragment_car

}